package com.worldtolearn.user.bean;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.SelectItem;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.worldtolearn.shoppingcart.bean.ShoppingCartMB;
//import com.worldtolearn.user.bu.AuthentificationBU;
import com.worldtolearn.user.bu.UserBu;
//import com.worldtolearn.user.bu.Authentification;
import com.worldtolearn.user.entity.User;

@Controller
@ManagedBean(name = "loginMB")
@SessionScoped
public class LoginMB {

	@Autowired
	private User user;

	@Autowired
	private UserBu userBu;
	// private AuthentificationBU authentification;

	@Autowired
	private ShoppingCartMB shoppingCartMB;

	@ManagedProperty(value = "createAccountMB")
	private CreateAccountMB accountMB;

	private List<SelectItem> items = null;

	private String currency = "EUR";
	private double taxChangeCoeff = 1.2;
	private double changeCoeff = 1.0;
	private String message;
	private String countrySelected;

	public LoginMB() {
		message = "Please login";

	}

	public String submit() {

		if (user.getMail()!= null && user.getPassword() != null) {

			HttpServletRequest request = (HttpServletRequest) FacesContext
					.getCurrentInstance().getExternalContext().getRequest();

			HttpSession session = ((HttpServletRequest) request)
					.getSession(false);
			accountMB = (session != null) ? (CreateAccountMB) session
					.getAttribute("createAccountMB") : null;
					
					session.setAttribute("loginMB", this);

			userBu.connect(user.getMail(), user.getPassword());
			
			if (userBu.isConnected()) {
				session.setAttribute("user", userBu.getUser());
			}else {
				return null;
			}
			
			
			
			@SuppressWarnings("unchecked")
			Enumeration<String> attrs = session.getAttributeNames();
			System.out.println("*****************kékona dans la session****************** " );
			while (attrs.hasMoreElements()) {
				String type = (String) attrs.nextElement();
				System.out.println("seesion type : " + type);
			}
			System.out.println("*****************fin de kékona dans la session****************** " );
			 String follow = "home";
			 return follow;
		}

		return null;
	}

	public String goToLogin() {
		return "login";
	}

	public String deconnexion() {
		userBu.disconnect();
		message = "Please login";
		user = new User();
		HttpServletRequest request = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		HttpSession session = ((HttpServletRequest) request).getSession(false);
		session.removeAttribute("loginMB");
		session.removeAttribute("createAccountMB");
		session.removeAttribute("user");
		return "home";
	}

	// *************** private methods ********************//

	private void changeChangeTaxCoeffMethod(String country) {

		try {
			URL url = new URL(
					"http://localhost:8080/AWorldToLearn/rest/a/total/price/"
							+ country);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String output;
			double taxChangeCoeff = 1.0;
			if ((output = reader.readLine()) != null) {
				try {
					taxChangeCoeff = Double.parseDouble(output);
					this.taxChangeCoeff = taxChangeCoeff;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			conn.disconnect();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void changeChangeCoeffMethod(String country) {

		try {
			URL url = new URL(
					"http://localhost:8080/AWorldToLearn/rest/a/total/change/"
							+ country);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String output;
			double changeCoeff = 1.0;
			if ((output = reader.readLine()) != null) {
				try {
					changeCoeff = Double.parseDouble(output);
					this.changeCoeff = changeCoeff;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			conn.disconnect();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void changeCurrencyMethod(String country) {
		try {
			URL url = new URL(
					"http://localhost:8080/AWorldToLearn/rest/a/total/currency/"
							+ country);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String output;
			if ((output = reader.readLine()) != null) {
				this.currency = output;
			}

			conn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// ****************** action called ****************//

	public List<SelectItem> getCountries() {
		System.out
				.println("on passe denas getcountries =+++++++++++++++++++++++++++++++++++++++++");
		if (items == null) {
			items = new ArrayList<SelectItem>();
			JSONParser parser = new JSONParser();
			try {
				URL url = new URL(
						"http://localhost:8080/AWorldToLearn/rest/a/total/allcountries/");
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setRequestMethod("GET");
				conn.setRequestProperty("Accept", "application/json");

				if (conn.getResponseCode() != 200) {
					throw new RuntimeException("Failed : HTTP error code : "
							+ conn.getResponseCode());
				}

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(conn.getInputStream()));
				String output;
				if ((output = reader.readLine()) != null) {


					Object obj = parser.parse(output);

					System.out.println("after parser" + obj);
					// JSONObject jsonObject = (JSONObject) obj;
					// loop array
					JSONArray chl = (JSONArray) obj;
					System.out.println("chl $$$$$$ *************** "
							+ chl.getClass().getName());
					System.out
							.println("***********************boucle json******************************");

					Iterator<Object> iterator = chl.iterator();
					
					while (iterator.hasNext()){
						JSONObject jsonObject2 = (JSONObject) iterator.next();
						String country = (String) jsonObject2.get("country");
						System.out.println("country ========== " + country);
						items.add(new SelectItem(country, country));
						System.out.println("country ========== ADD OK");
					}
					System.out.println("country iterator out========== ADD all OK");
					
//					for (Object obj2 : chl) {
//						JSONObject jsonObject2 = (JSONObject) obj2;
//						String country = (String) jsonObject2.get("country");
//						System.out.println("country ========== " + country);
//						items.add(new SelectItem(country, country));
//					}
					// try{
					// this.taxChangeCoeff=taxChangeCoeff;
					// }
					// catch(Exception e){
					// e.printStackTrace();
					// }
				}

				conn.disconnect();

				System.out.println("deconnected CONN");
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("------------------------------- -- -- ------------- ------ --------------- -taille de items : "+items.size());
		for (SelectItem s : items) {
			System.out.println("le item dans le tableau : "+s.toString());
		}
		return items;
	}

	public void countryChanged(ValueChangeEvent e) {
		this.countrySelected = e.getNewValue().toString();
		changeCurrencyMethod(this.countrySelected);
		changeChangeTaxCoeffMethod(this.countrySelected);
		changeChangeCoeffMethod(this.countrySelected);
	}

	// *************** get setter *******************//
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserBu getUserBu() {
		return userBu;
	}

	public void setUserBu(UserBu userBu) {
		this.userBu = userBu;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getCurrency() {
		return currency;
	}

	public double getTaxChangeCoeff() {
		return taxChangeCoeff;
	}

	public double getChangeCoeff() {
		return changeCoeff;
	}

	public String getCountrySelected() {
		return countrySelected;
	}

	public void setCountrySelected(String countrySelectedParam) {
		countrySelected = countrySelectedParam;
	}

}
